package com.hfmall.service.impl;

import com.hfmall.entity.HfAddress;
import com.hfmall.mapper.HfAddressMapper;
import com.hfmall.service.IHfAddressService;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liclo
 * @since 2021-08-12
 */
@Service
public class HfAddressServiceImpl extends ServiceImpl<HfAddressMapper, HfAddress> implements IHfAddressService {

    @Resource
    private HfAddressMapper mapper;

    @Override
    public List<HfAddress> getByUser(int userId) {
        return mapper.getByUser(userId);
    }

    @Override
    public void add(HfAddress address) {
        if("true".equals(address.getIsdefault())){
            //添加时直接设置为默认地址
            address.setIsdefault("y");
            //获取当前默认地址
          HfAddress defAddr = mapper.getDefault(address.getUserId());
          //修改为非默认
          defAddr.setIsdefault("n");
          mapper.updateById(defAddr);
        }else {
            address.setIsdefault("n");
        }
        System.out.println(address.getUserId());
        mapper.insert(address);



    }

    @Override
    public void setDefault(int id,int userId) {
        HfAddress defAddr = mapper.getDefault(userId);
        //修改为非默认
        defAddr.setIsdefault("n");
        mapper.updateById(defAddr);

        mapper.setDefault(id);
    }

    @Override
    public void update(HfAddress address) {
        if("true".equals(address.getIsdefault()) || "y".equals(address.getIsdefault())){
            //添加时直接设置为默认地址
            address.setIsdefault("y");
            //获取当前默认地址
            HfAddress defAddr = mapper.getDefault(1);
            //修改为非默认
            defAddr.setIsdefault("n");
            mapper.updateById(defAddr);
        }else {
            address.setIsdefault("n");
        }


        mapper.updateById(address);
    }

    @Resource
    HfAddressMapper hfAddressMapper;
    @Override
   public List<HfAddress> getAllHfAddress(){
        return hfAddressMapper.getAllHfAddress();
    }
}
